import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Layout, Input, Button, Table, Modal, Pagination } from 'antd';
import { DEFAULT_PAGE_SIZE, DEFAULT_INVALID_STATE, DEFAULT_VALID_STATE } from '@/constants';
import { CONST_PERMISSION_CODE_DEPARTMENT_ADD, CONST_PERMISSION_CODE_DEPARTMENT_UPD, CONST_PERMISSION_CODE_DEPARTMENT_STOP } from '@/constants';
import styles from './index.less';

import Edit from './edit';
import UnitDepartment from '../Common/UnitDepartment';

const { Sider, Content } = Layout;
const { confirm } = Modal;

class Index extends PureComponent {
  constructor(props) {
    super(props);
    this.modularName = 'department';
    const { global } = props;
    const { currentUnit = {} } = global;
    this.state = {
      currentUnitName: currentUnit.unit_name || '',
      query: {
        state: DEFAULT_VALID_STATE,
        unit_id: {
          id: currentUnit.id || -1
        }
      },
      units: []
    }
  }

  componentDidMount() {
    this.props.dispatch({
      type: `unit/queryData`,
      payload: {
        state: DEFAULT_VALID_STATE,
        current: 1,
        pageSize: 10000,
        callback: (data) => {
          this.setState({ units: data })
        }
      }
    });
    this.queryData(1, DEFAULT_PAGE_SIZE);
  }

  componentWillUnmount() {
    this.props.dispatch({ type: `${this.modularName}/clear` });
  }

  appendBtnClick = () => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '新增部门', editData: {} }
    })
  }

  detailBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '查看部门', editData: record }
    })
  }

  editBtnClick = (record) => {
    this.props.dispatch({
      type: `${this.modularName}/changeState`,
      payload: { visible: '编辑部门', editData: record }
    })
  }

  stopBtnClick = (record) => {
    confirm({
      title: '是否确认停用部门?',
      content: Array.isArray(record) ? undefined : `部门 [${record.dept_name}]`,
      onOk: () => {
        const { query = {} } = this.state;
        const { dispatch, modular } = this.props;
        const { current, pageSize } = modular;

        this.setState({ selectedRows: [] });
        dispatch({
          type: `${this.modularName}/deleteData`,
          payload: {
            data: Array.isArray(record) ? record.map(item => ({ ...item, state: DEFAULT_INVALID_STATE })) : { ...record, state: DEFAULT_INVALID_STATE },
            ...query,
            current,
            pageSize
          }
        });
      },
      onCancel() { }
    });
  }

  searchBtnClick = () => {
    const { modular } = this.props;
    const { pageSize = DEFAULT_PAGE_SIZE } = modular;

    this.queryData(1, pageSize);
  }

  onChange = (current, pageSize) => {
    this.queryData(current, pageSize);
  }

  onShowSizeChange = (current, pageSize) => {
    this.onChange(1, pageSize);
  }

  onOk = () => {
    const { query = {} } = this.state;
    const { dispatch, form, modular } = this.props;
    const { editData = {}, current, pageSize } = modular;

    form.validateFields((err, values) => {
      if (!err) {
        const data = {
          ...editData,
          ...values
        };
        if (!editData.id) {
          data.state = DEFAULT_VALID_STATE;
        }
        dispatch({
          type: `${this.modularName}/saveOrUpdateData`,
          payload: {
            id: editData.id,
            data,
            ...query,
            current,
            pageSize
          }
        });
      }
    });
  }

  onTreeSelect = (id, name, type) => {
    if (type === 'unit') {
      const { query = {} } = this.state;
      const { modular } = this.props;
      const { pageSize = DEFAULT_PAGE_SIZE } = modular;

      this.setState({ currentUnitName: name || '', query: { ...query, dept_name: undefined, unit_id: { id: id || -1 } } }, () => {
        this.queryData(1, pageSize);
      });
    }
  }

  queryData = (current, pageSize) => {
    const { query = {} } = this.state;

    this.props.dispatch({
      type: `${this.modularName}/queryData`,
      payload: {
        ...query,
        current,
        pageSize
      }
    });
  }

  render() {
    const { currentUnitName, query = {}, selectedRows = [], units = [] } = this.state;
    const { dispatch, form, loading, global, modular } = this.props;
    const { isAdmin, userPermissions = [] } = global;
    const { data, current = 1, pageSize = DEFAULT_PAGE_SIZE, total = 0, rowKey, visible, editData = {} } = modular;

    const columns = [
      {
        title: '单位名称',
        dataIndex: 'unit_name',
        ellipsis: true,
        width: 200,
        render: (text, record) => {
          if (record && record.unit_id) {
            return record.unit_id.unit_name
          }
        }
      },
      {
        title: '部门名称',
        dataIndex: 'dept_name',
        ellipsis: true,
        width: 200,
      },
      {
        title: '操作',
        dataIndex: 'operate',
        align: 'center',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          return (
            <div className={styles.common_span_group}>
              <span onClick={this.detailBtnClick.bind(this, record)}>查看</span>
              {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_DEPARTMENT_UPD) &&
                <span onClick={this.editBtnClick.bind(this, record)}>编辑</span>
              }
              {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_DEPARTMENT_STOP) &&
                <span style={{ color: '#ff4d4f' }} onClick={this.stopBtnClick.bind(this, record)}>停用</span>
              }
            </div>
          );
        }
      }
    ];

    return (
      <Layout className={styles.basic_layout_wrapper}>
        {isAdmin &&
          <Sider
            className={styles.sider_wrapper}
            style={{
              overflow: 'hidden',
              position: 'fixed',
              // left: 24,
            }}
            width={256}
          >
            <div>
              <UnitDepartment hasChild={false} loading={!!loading.effects[`unit/queryData`]} currentId={query.unit_id.id} units={units} onTreeSelect={this.onTreeSelect} />
            </div>
          </Sider>
        }
        <Layout style={{ marginLeft: isAdmin ? 256 : 0 }}>
          <div className={styles.title}>
            当前单位: <span style={{ color: 'rgb(27, 139, 236)' }}>{currentUnitName}</span>
          </div>
          <div className={styles.conditions_wrapper}>
            <Input placeholder='部门名称' style={{ width: 240, marginRight: 16 }} value={query.dept_name} onChange={e => this.setState({ query: { ...query, dept_name: e.target.value || undefined } })} />
            <Button icon='search' type='primary' onClick={this.searchBtnClick}>搜索</Button>
          </div>
          <Content className={styles.conditions_wrapper} style={{ margin: 0 }}>
            <Layout style={{ backgroundColor: 'transparent', height: '100%' }}>
              <div>
                {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_DEPARTMENT_ADD) &&
                  <Button icon='plus' type='primary' style={{ width: 110, marginRight: 16, marginBottom: 16 }} onClick={this.appendBtnClick}>新增部门</Button>
                }
                {Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_DEPARTMENT_STOP) &&
                  <Button icon='delete' type='danger' style={{ marginBottom: 16 }} onClick={selectedRows && selectedRows.length > 0 ? this.stopBtnClick.bind(this, selectedRows) : undefined}>批量停用{selectedRows && selectedRows.length > 0 ? `(${selectedRows.length})` : ''}</Button>
                }
              </div>
              <Content className={styles.common_table_wrapper}>
                <Table
                  columns={columns}
                  dataSource={data}
                  loading={!!loading.effects[`${this.modularName}/queryData`] || !!loading.effects[`${this.modularName}/deleteData`]}
                  pagination={false}
                  rowKey={rowKey}
                  rowSelection={
                    Array.isArray(userPermissions) && userPermissions.includes(CONST_PERMISSION_CODE_DEPARTMENT_STOP) ?
                      {
                        onChange: (selectedRowKeys, rows) => {
                          this.setState({ selectedRows: [...selectedRows.filter(item => selectedRowKeys.includes(item.id) && !rows.map(row => row.id).includes(item.id)), ...rows] })
                        }
                      } : null
                  }
                  scroll={{ x: true }}
                />
              </Content>
              <div style={{ marginTop: 16 }}>
                <Pagination
                  current={current}
                  pageSize={pageSize}
                  total={total}
                  showQuickJumper
                  showSizeChanger
                  showTotal={(total, range) => `共有 ${total} 条数据`}
                  onChange={this.onChange}
                  onShowSizeChange={this.onShowSizeChange}
                />
              </div>
            </Layout>
          </Content>
        </Layout>
        <Modal
          centered
          destroyOnClose
          maskClosable={false}
          title={visible}
          visible={!!visible}
          wrapClassName={styles.common_modal_wrapper}
          width={480}
          okButtonProps={visible === '查看部门' ? { style: { display: 'none' } } : {}}
          onOk={this.onOk}
          onCancel={() => {
            dispatch({
              type: `${this.modularName}/changeState`,
              payload: {
                visible: undefined, editData: {}
              }
            })
          }}
        >
          <Edit form={form} data={editData} currentUnit={{ id: query.unit_id.id, unit_name: currentUnitName }} disabled={visible === '查看部门'} />
        </Modal>
      </Layout>
    );
  }
}

export default connect(({ loading, global, department }) => ({ loading, global, modular: department }))(Form.create()(Index));